<template>
  <div class="plan-entry bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">预约申请</h2>


    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchPlans" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button type="primary" @click="openAddDialog">申请</el-button>
      <el-button @click="deleteSelected">删除</el-button>
      <!-- <button @click="openImportDialog" class="bg-accent text-accent-foreground px-4 py-2 rounded">导入</button> -->
      <el-button @click="exportData(planData, '预约申请', selectedIds)">导出</el-button>

    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedPlanData" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="SYSTEM_CODE" label="系统单号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LICENSE_PLATE" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_VEHICLES_TYPE" label="车辆类型" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_MATERIAL_NAME" label="危化品名称" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_MATERIAL_TYPE" label="危化品类别" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="WEIGHT" label="数量(KG)" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_PHONE" label="联系方式" header-align="center" align="center"></el-table-column>
        <el-table-column prop="STATE" label="申请状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.STATE)">
              {{ scope.row.STATE == 0 ? '已提交' : scope.row.STATE == 1 ? '已通过' : '未通过' }}
            </div>

          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.STATE == 0" type="primary" size="small" @click="openEditDialog(scope.row)"
              link>编辑</el-button>
            <el-button v-else type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="planData.length" :tableData="planData" @alltabledata="alltabledata" />
    <!-- Add Plan Dialog -->
    <el-dialog width="650px" class="dialog-from" v-model="isAddDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'"
      destroy-on-close align-center :before-close="closeAddDialog">
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">车牌号码</label>
              <el-input type="text" id="staffCode" v-model="newRecord.LICENSE_PLATE" required class="input" />
            </div>
            <div>
              <label for="staffName" class="block text-sm font-medium text-muted-foreground">车辆类型</label>

              <el-select v-model="newRecord.HAZARDOUS_VEHICLES_TYPE" placeholder="请选择" clearable>
                <!-- <el-option label="开放" value='1' /> -->
                <!-- <el-option label="油管车" value='油管车' /> -->
                <el-option value="易燃气体罐车">易燃气体罐车</el-option>
                <el-option value="易燃液体罐车">易燃液体罐车</el-option>
                <el-option value="易燃固体罐车">易燃固体罐车</el-option>
                <el-option value="易爆气体罐车">易爆气体罐车</el-option>
                <el-option value="易爆液体罐车">易爆液体罐车</el-option>
                <el-option value="易爆固体罐车">易爆固体罐车</el-option>
              </el-select>
            </div>
            <div>
              <label for="idCard" class="block text-sm font-medium text-muted-foreground">危化品名称</label>
              <el-input type="text" id="idCard" v-model="newRecord.HAZARDOUS_MATERIAL_NAME" required class="input" />
            </div>
            <div>
              <label for="staffGender" class="block text-sm font-medium text-muted-foreground">危化品类别</label>
              <el-input type="text" id="TELEPHONE" v-model="newRecord.HAZARDOUS_MATERIAL_TYPE" required class="input" />
            </div>
            <div>
              <label for="TELEPHONE" class="block text-sm font-medium text-muted-foreground">数量(KG)</label>
              <el-input type="text" id="staffName" v-model="newRecord.WEIGHT" required class="input" />
            </div>
          </div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>驾驶员信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">驾驶员姓名</label>
              <el-input type="text" id="staffCode" v-model="newRecord.DRIVER_NAME" required class="input" />
            </div>
            <div>
              <label for="staffName" class="block text-sm font-medium text-muted-foreground">证件号码</label>
              <el-input type="text" id="idCard" v-model="newRecord.DRIVER_ID_NUMBER" required class="input" />
            </div>
            <div>
              <label for="idCard" class="block text-sm font-medium text-muted-foreground">联系方式</label>
              <el-input type="text" id="idCard" v-model="newRecord.DRIVER_PHONE" required class="input" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">驾驶证</label>

              <div v-if="isEditing" style="margin:10px 0">

                <span v-for="item in imgdata" :key="item">

                  <el-image style="width: 100px; height: 100px" lazy :src="item" :zoom-rate="1.2" :max-scale="7"
                    :min-scale="0.2" :initial-index="0" fit="cover" />
                </span>


              </div>
              <input type="file" accept=".png,.jpg,.jpeg" id="importFile" @change="handleRISK_HAS"
                class="mt-1 block w-full">
              <!-- accept=".csv, .xlsx" -->
            </div>

          </div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>其他信息</span>
          </div>
          <div>
            <label class="block text-sm font-medium text-muted-foreground">备注：</label>
            <el-input type="text" v-model="newRecord.STAMP" required class="input" />
          </div>
        </div>
        <hr style="margin:8px" />
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click="addNewPlan" style="width: 75px; height: 30px;">确认</el-button>
          <el-button @click="closeAddDialog" style="width: 75px; height: 30px;">取消</el-button>
        </div>
      </form>
    </el-dialog>
    <!-- Import Dialog -->
    <el-dialog width="400px" class="dialog-from" v-model="isImportDialogOpen" title="导入" destroy-on-close align-center
      :before-close="closeImportDialog">
      <div class="mb-4">
        <label for="importFile" class="block text-sm font-medium">选择文件</label>
        <input type="file" id="importFile" @change="handleFileUpload" accept=".csv, .xlsx" class="mt-1 block w-full">
      </div>
      <div class="mt-4 flex justify-end space-x-2">
        <el-button @click="closeImportDialog"
          class="bg-secondary text-secondary-foreground px-4 py-2 rounded">取消</el-button>
        <el-button v-loading.fullscreen.lock="fullscreenLoading" @click="confirmImport"
          class="bg-accent text-accent-foreground px-4 py-2 rounded" type="primary">确认导入</el-button>
      </div>

    </el-dialog>
    <!-- View Details Dialog -->
    <el-dialog width="650px" class="dialog-from" v-model="isViewDialogOpen" title="查看" destroy-on-close align-center
      :before-close="closeViewDialog">
      <div class="body-item">
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="box-content">
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">车牌号码:</span>
                <span class="auto-wrap">{{ selectedItem.LICENSE_PLATE }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">车辆类型:</span>
                <span class="auto-wrap">{{ selectedItem.HAZARDOUS_VEHICLES_TYPE }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">危化品名称:</span>
                <span class="auto-wrap">{{ selectedItem.HAZARDOUS_MATERIAL_NAME }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">危化品类别:</span>
                <span class="auto-wrap">{{ selectedItem.HAZARDOUS_MATERIAL_TYPE }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">数量(KG):</span>
                <span class="auto-wrap">{{ selectedItem.WEIGHT }}</span>
              </div>
            </el-col>
            <el-col :span="6">

            </el-col>
          </el-row>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>驾驶员信息</span>
        </div>
        <div class="box-content">
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">驾驶员姓名:</span>
                <span class="auto-wrap">{{ selectedItem.DRIVER_NAME }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">证件号码:</span>
                <span class="auto-wrap">{{ selectedItem.DRIVER_ID_NUMBER }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div>
                <span class="no-wrap">联系方式:</span>
                <span class="auto-wrap">{{ selectedItem.DRIVER_PHONE }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="6">
              <div>
                <span class="no-wrap">驾驶证:</span>
                <span v-for="item in imgdata" :key="item">
                  <el-image style="width: 100px; height: 100px" lazy :src="item" :zoom-rate="1.2" :max-scale="7"
                    :min-scale="0.2" :initial-index="0" fit="cover" />
                </span>

              </div>
            </el-col>
            <el-col :span="6">
            </el-col>
            <el-col :span="6">
            </el-col>
          </el-row>

        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>其他信息</span>
        </div>
        <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
          <el-col :span="19">
            <div>
              <span class="no-wrap">备注:</span>
              <span class="auto-wrap">{{ selectedItem.STAMP }}</span>
            </div>
          </el-col>
          <el-col :span="1">
          </el-col>
        </el-row>
      </div>

    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import axios from 'axios'
import { dayjs, ElLoading } from "element-plus"
const { proxy } = getCurrentInstance()
import { exportData, uploadfile, checkval } from '#/utils/exportfile.js'
const apiBaseUrl = ref(proxy.$currentUrl + '/api/hazardous-vehicle-booking')

// 搜索相
const search = ref({
  LICENSE_PLATE: '',
  DRIVER_NAME: '',
  STATE: '',
})
const formItems = ref([
  {
    label: '车牌号码：',
    model: 'LICENSE_PLATE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '申请状态：',
    model: 'STATE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '未通过', value: '2' },
      { label: '已通过', value: '1' },
      { label: '已提交', value: '0' },
    ],
  },

])
const imgdata = ref([])
// 数据相关
const isEditing = ref(false)
const planData = ref([])
const selectedIds = ref([])
const selectedItem = ref(null) // 添加这行
const loading = ref(false)
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const importFile = ref(null)
const rowKey = (row) => row.ID // 设置行的唯一标识
// 对话框状态
const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isViewDialogOpen = ref(false) // 添加这行
const isEditDialogOpen = ref(false) // 添加这行
const table = ref()
// 新记录
const newRecord = ref({

  files: []
})

const displayedPlanData = ref([])
const alltabledata = (data) => {
  displayedPlanData.value = data

}
// API 调用函数
const searchPlans = async () => {
  try {
    displayedPlanData.value = []
    // loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    planData.value = response.data.map(equipment => ({ ...equipment, selected: false }))
    // loading.value = false
  } catch (error) {
    console.error('搜索记录失败:', error)
    alert('搜索记录失败')
  }
}

// 打开录入对话框
const openAddDialog = () => {
  isAddDialogOpen.value = true
}

// 关闭录入对框
const closeAddDialog = () => {
  newRecord.value = {
    files:[]
  }
  isEditing.value = false
  isAddDialogOpen.value = false
  imgdata.value = []
}
const fullscreenLoading = ref(false)
const importHeaders = ref([])
const importData = ref([])
const handleRISK_HAS = (event) => {
  newRecord.value.files = []
  const files = Array.from(event.target.files)
  newRecord.value.files = [files[0]]

}


// 添加新预案
const addNewPlan = async () => {


  if (checkval([
    'HAZARDOUS_VEHICLES_TYPE',
    'LICENSE_PLATE',
    'HAZARDOUS_MATERIAL_NAME',
    'HAZARDOUS_MATERIAL_TYPE',
    'DRIVER_NAME',
    'DRIVER_PHONE',
    'WEIGHT',
    'DRIVER_ID_NUMBER',
    'STAMP',], '预约申请', newRecord.value)) {
    return
  }

  if (!newRecord.value.files) {
    alert('驾驶证不能为空')
    return
  }



  try {
    const formData = new FormData()
    for (const key in newRecord.value) {
      if (key !== 'files') {
        formData.append(key, newRecord.value[key])
      }
    }
    if (newRecord.value?.files) {
      newRecord.value.files.forEach((file, index) => {
        formData.append(`files[${index}]`, file)
      })
    }
    if (!isEditing.value) {
      const response = await axios.post(apiBaseUrl.value, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert('申请成功')
    } else {
      const response = await axios.put(apiBaseUrl.value + '/' + newRecord.value.ID, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert('编辑成功')
    }

    closeAddDialog()
    await searchPlans()
  } catch (error) {
    console.error('创建失败:', error)
    alert('创建失败: ' + (error.response?.data?.message || error.message))
  }
}

// 重置搜索
const resetSearch = () => {
  search.value = {
    LICENSE_PLATE: '',
    DRIVER_NAME: '',
    STATE: '',
  }
  searchPlans()
}

// 删除选中的预案
const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(item => {
        axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      }
      ))
      alert('删除成功')
      selectedIds.value = []
      table.value.clearSelection()
      await searchPlans()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}


// 打开导入对话框
const openImportDialog = () => {
  isImportDialogOpen.value = true
  console.log('Import dialog opened') // 添加日志
}

// 关闭导入对话框
const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
  console.log('Import dialog closed') // 添加日志
}


// 文件上传处理
const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
  console.log('File selected:', importFile.value?.name) // 添加日志
}
const confirmImport = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    loading.close()
    alert('导入成功')
    closeImportDialog()
    searchPlans()
  } catch (error) {
    loading.close()
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }

}





// 查看预案详情
const viewDetails = async (item) => {

  selectedItem.value = { ...item }

  isViewDialogOpen.value = true
  const response = await axios.get(`${apiBaseUrl.value}/download/${selectedItem.value.DRIVING_LICENSE}`)
  imgdata.value.push(response.data.url)
}

// 关闭查看详情对话框
const closeViewDialog = () => {
  isViewDialogOpen.value = false
  selectedItem.value = {}
}

// 编辑预案
const openEditDialog = async (item) => {

  for (const key in item) {
    if (/DATE/.test(key) && key != 'UPDATE_BY') {
      item[key] = dayjs(item[key]).format('YYYY-MM-DD')
    }
  }
  item.PLAN_REVIEWED_STATE = String(item.PLAN_REVIEWED_STATE)
  item.RISK_HAS_TOLD_YES_OR_NO = String(item.RISK_HAS_TOLD_YES_OR_NO)
  newRecord.value = { ...item }
  newRecord.value.files = []
  const response = await axios.get(`${apiBaseUrl.value}/download/${newRecord.value.DRIVING_LICENSE}`)
  imgdata.value.push(response.data.url)
  isEditing.value = true
  isAddDialogOpen.value = true
}


const updatePlan = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${selectedItem.value.id}`, selectedItem.value)
    alert(response.data.message || '更新成功')

    await searchPlans()
  } catch (error) {
    console.error('更新记录失败:', error)
    alert('更新记录失败: ' + (error.response?.data?.message || error.message))
  }
}

// 发布预案
const publishPlan = async (id) => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${id}`, { status: '已发布' })
    alert(response.data.message || '发布成功')
    await searchPlans()
  } catch (error) {
    console.error('发布失败:', error)
    alert('发布失败: ' + (error.response?.data?.message || error.message))
  }
}

// 删除预案
const deletePlan = async (id) => {
  if (confirm('确定要删除这条记录吗？')) {
    try {
      const response = await axios.delete(`${apiBaseUrl.value}/${id}`)
      alert(response.data.message || '删除成功')
      await searchPlans()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 生命周期钩子
onMounted(() => {
  searchPlans()
})
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const getStatusClass = (status) => {
  const classMap = {
    '0': 'bg-yellow-100 text-yellow-800',
    '1': 'bg-green-100 text-green-800',
    '2': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}
</script>

<style scoped>
/* 移除所有现有的样式 */
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}
</style>
